package cn.kogee.org.service.impl;

import cn.kogee.basic.service.impl.BaseServiceImpl;
import cn.kogee.org.domain.Department;
import cn.kogee.org.mapper.DepartmentMapper;
import cn.kogee.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Transactional
    @Override
    public void add(Department department) {
        departmentMapper.save(department);
        if(department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            Department departments = departmentMapper.loadById(department.getParent_id());
            department.setDirPath(departments.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }


    @Transactional
    @Override
    public void update(Department department) {
        if(department.getParent_id()==null){
            department.setDirPath("/"+department.getId());
        }else {
            Department departments = departmentMapper.loadById(department.getParent_id());
            department.setDirPath(departments.getDirPath()+"/"+department.getId());
        }
        departmentMapper.update(department);
    }


    /**
     * 上级部门无限树级
     * @return
     */
    @Override
    public List<Department> deptTree() {
        //查询出所有部门数据
        List<Department> departments = departmentMapper.loadAll();
        //将上级部门数据保存到map中
        Map<Long, Department> map = new HashMap<>();
        //遍历所有部门数据，以部门ID作为Key,整个部门对象作为value存入map中
        for (Department department : departments) {
            map.put(department.getId(),department);
        }
        //创建新的部门集合
        ArrayList<Department> deptTree = new ArrayList<>();
        //再次遍历所有部门数据
        for (Department department : departments) {
            if(department.getParent_id()==null){//如果上级部门ID为null说明为顶级部门
                deptTree.add(department);
            }else {
                //如果有上级部门ID说明不是顶级部门通过上级部门ID作为key拿到上级部门数据
                Department parDepartment = map.get(department.getParent_id());
                //将部门数据设置到上级部门Children中
                parDepartment.getChildren().add(department);
            }
        }


        return deptTree;
    }
}
